package com.qindachang.bluetoothlelibrary.ui.test.Agree;

import com.pynr.kaiyiapp.config.Global;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;


public class Agreement {
    //    Int16 相当于short占2字节
//    Int32相当于int占4字节
//    Int64相当于long
//    long 占8字节
//    Byte相当于 byte 0~255
//    WORD 等于unsigned
//    short 0~65535

    /**
     * 顺序整数 浮点数 布尔 字符串
     *
     * @param requestId
     * @param deviceCode
     * @param cParams
     * @param paramStrings
     * @return
     * @throws Exception
     */
    public static byte[] blueCollectData(int requestId, int deviceCode, ArrayList<Integer> cParams, ArrayList<String> paramStrings, int size) throws Exception {
        //包头4字节
        byte[] bytes = new byte[size];
        for (int i = 0; i < 4; i++) {
            bytes[i] = 35;
        }
        int tmpLen = 0;
        //长度 4 5
        tmpLen = 2;
        int length = size - 4 - 2;
        byte[] lenByte = new byte[tmpLen];
        lenByte = BitConverterUtil.intToHexByteArray(length, tmpLen);
        System.arraycopy(lenByte, 0, bytes, 4, tmpLen);
        //指令6
        int offset = 6;
        tmpLen = 4;
        byte[] orderByte = new byte[4];
        orderByte = BitConverterUtil.intToHexByteArray(requestId, tmpLen);
        System.arraycopy(orderByte, 0, bytes, offset, tmpLen);
        System.out.println(BitConverterUtil.byteArrayToHexStr(orderByte));
        offset += tmpLen;
        //设备编号
        byte[] devCodeByte = new byte[4];
        tmpLen = 4;
        devCodeByte = BitConverterUtil.intToHexByteArray(deviceCode, tmpLen);
        System.arraycopy(devCodeByte, 0, bytes, offset, tmpLen);
        System.out.println(BitConverterUtil.byteArrayToHexStr(devCodeByte));
        offset += tmpLen;
        //整数
        byte[] emptyNumByte = new byte[1];
        emptyNumByte = BitConverterUtil.intToHexByteArray(0, 1);
        //int数据个数
        Integer iInt = cParams.get(AgreeDefine.int_index);
        if (iInt.intValue() != 0) {
            String[] splitStrs = paramStrings.get(AgreeDefine.int_index).split(AgreeDefine.split_sign);
            if (iInt.intValue() == splitStrs.length) {
                int number = splitStrs.length;
                byte[] numByte = new byte[1];
                numByte = BitConverterUtil.intToHexByteArray(number, 1);
                System.arraycopy(numByte, 0, bytes, offset, 1);
                offset++;
                for (int i = 0; i < splitStrs.length; i++) {
                    tmpLen = 4;
                    int tmp = Integer.valueOf(splitStrs[i]);
                    byte[] tmpByte = new byte[4];
                    tmpByte = BitConverterUtil.intToHexByteArray(tmp, tmpLen);
                    System.arraycopy(tmpByte, 0, bytes, offset, tmpLen);
                    offset += tmpLen;
                    System.out.println(BitConverterUtil.byteArrayToHexStr(tmpByte));
                    System.out.println(tmpLen);
                }
            } else {
                //数据个数有误
                System.arraycopy(emptyNumByte, 0, bytes, offset, emptyNumByte.length);
                offset += emptyNumByte.length;
            }
        } else {
            System.arraycopy(emptyNumByte, 0, bytes, offset, emptyNumByte.length);
            offset += emptyNumByte.length;
        }

        //浮点
        Integer fInt = cParams.get(AgreeDefine.float_index);
        if (fInt.intValue() != 0) {
            String[] splitStrs = paramStrings.get(AgreeDefine.float_index).split(AgreeDefine.split_sign);
            if (splitStrs.length != 0) {
                int number = splitStrs.length;
                byte[] numByte = new byte[1];
                numByte = BitConverterUtil.intToHexByteArray(number, 1);
                System.arraycopy(numByte, 0, bytes, offset, 1);
                offset++;
                for (int i = 0; i < splitStrs.length; i++) {
                    tmpLen = 8;
                    double tmp = Double.valueOf(splitStrs[i]).doubleValue();
                    byte[] tmpByte = new byte[tmpLen];
                    tmpByte = BitConverterUtil.doubleToBytes(tmp);
                    System.arraycopy(tmpByte, 0, bytes, offset, tmpLen);
                    offset += tmpLen;
                    System.out.println(BitConverterUtil.bytesToDouble(tmpByte));
                    System.out.println(tmpLen);
                }
            } else {
                System.arraycopy(emptyNumByte, 0, bytes, offset, emptyNumByte.length);
                offset += emptyNumByte.length;
            }
        } else {
            System.arraycopy(emptyNumByte, 0, bytes, offset, emptyNumByte.length);
            offset += emptyNumByte.length;
        }

        //无布尔
        Integer bInt = cParams.get(AgreeDefine.bool_index);
        if (bInt.intValue() != 0) {
            String[] splitStrs = paramStrings.get(AgreeDefine.bool_index).split(AgreeDefine.split_sign);
            if (splitStrs.length != 0) {
                int number = splitStrs.length;
                byte[] numByte = new byte[1];
                numByte = BitConverterUtil.intToHexByteArray(number, 1);
                System.arraycopy(numByte, 0, bytes, offset, 1);
                offset++;
                for (int i = 0; i < splitStrs.length; i++) {
                    tmpLen = 1;
                    Integer tmp = Integer.valueOf(splitStrs[i]);
                    byte[] tmpByte = new byte[tmpLen];
                    tmpByte = BitConverterUtil.intToHexByteArray(tmp, tmpLen);
                    System.arraycopy(tmpByte, 0, bytes, offset, tmpLen);
                    offset += tmpLen;
                    System.out.println(BitConverterUtil.byteArrayToHexStr(tmpByte));
                    System.out.println(tmpLen);
                }
            } else {
                System.arraycopy(emptyNumByte, 0, bytes, offset, emptyNumByte.length);
                offset += emptyNumByte.length;
            }
        } else {
            System.arraycopy(emptyNumByte, 0, bytes, offset, emptyNumByte.length);
            offset += emptyNumByte.length;
        }
        //字符串
        Integer sInt = cParams.get(AgreeDefine.str_index);
        if (sInt.intValue() != 0) {
            String[] splitStrs = paramStrings.get(AgreeDefine.str_index).split(AgreeDefine.split_sign);
            if (splitStrs.length != 0) {
                int number = splitStrs.length;
                byte[] numByte = new byte[1];
                numByte = BitConverterUtil.intToHexByteArray(number, 1);
                System.arraycopy(numByte, 0, bytes, offset, 1);
                offset++;
                for (int i = 0; i < splitStrs.length; i++) {
                    tmpLen = 16;
                    String tmp = splitStrs[i];
                    byte[] tmpByte = new byte[tmpLen];
                    tmpByte = BitConverterUtil.stringToHexByteArray(tmp, tmpLen, false);
                    System.arraycopy(tmpByte, 0, bytes, offset, tmpLen);
                    offset += tmpLen;
                    System.out.println(BitConverterUtil.byteArrayToHexStr(tmpByte));
                    System.out.println(tmpLen);
                }
            } else {
                System.arraycopy(emptyNumByte, 0, bytes, offset, emptyNumByte.length);
                offset += emptyNumByte.length;
            }
        } else {
            System.arraycopy(emptyNumByte, 0, bytes, offset, emptyNumByte.length);
            offset += emptyNumByte.length;
        }
        //时间戳
        tmpLen = 8;
        byte[] time = new byte[tmpLen];
        time = getTimestamp();
        System.arraycopy(time, 0, bytes, offset, tmpLen);
        offset += tmpLen;
        //校验码
        tmpLen = 2;
        byte[] crc = new byte[tmpLen];
        crc = CRC.getCRC16(bytes, bytes.length - tmpLen);
        System.arraycopy(crc, 0, bytes, offset, tmpLen);
        return bytes;
    }


    /**
     * @param
     */
    public static String[] analysisDataPackageByte(byte[] bytes) {
        if (bytes == null || bytes.length < 6) {
            return null;
        }

        if (bytes[0] != 35 || bytes[1] != 35 || bytes[2] != 35 || bytes[3] != 35) {//包头
            return null;
        }

        int length = BitConverter.ToUInt16(BitConverterUtil.subBytes(bytes, 4, 2), 0);
        if (6 + length != bytes.length) {//指令
            return null;
        }

        byte[] crc = CRC.getCRC16(bytes, bytes.length - 2);
        if (crc[0] != bytes[bytes.length - 2] || crc[1] != bytes[bytes.length - 1]) {
            return null;
        }

        String deviceCode = String.valueOf(BitConverterUtil.hexByteArrayToInt(BitConverterUtil.subBytes(bytes, 10, 4)));
        if (!Global.getInstance().getBlueConnectDevice().equals(deviceCode)) {
            return null;
        }

        String[] values = new String[10];
        int index = 0;
        int offset = 14;

        // int
        byte count = bytes[offset];
        offset += 1;
        for (int i = 0; i < count; i++) {
            int temp = BitConverter.ToInt32(BitConverterUtil.subBytes(bytes, offset, 4), 0);
            values[index++] = String.valueOf(temp);
            offset += 4;
        }

        // Double
        count = bytes[offset];
        offset += 1;
        for (int i = 0; i < count; i++) {
            double temp = BitConverter.ToDouble(BitConverterUtil.subBytes(bytes, offset, 8), 0);
            values[index++] = String.valueOf(temp);
            offset += 8;
        }

        // Boolean
        count = bytes[offset];
        offset += 1;
        for (int i = 0; i < count; i++) {
            values[index++] = (bytes[offset] >> i & 1) == 1 ? "1" : "0";
        }

        // String
        count = bytes[offset];
        offset += 1;
        for (int i = 0; i < count; i++) {
            //子数组转换为ASCII字符
            byte[] temp = BitConverterUtil.subBytes(bytes, offset, 16);
            values[index++] = toStringHex(temp).trim();
            offset += 16;
        }

        return values;
    }

    /**
     * 十六进制转字符串ASCII
     *
     * @param sub
     * @return
     */
    public static String toStringHex(byte[] sub) {
        String s = BitConverterUtil.byteArrayToHexStr(sub);
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "ASCII");
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }

    /**
     * 64位双精度浮点数 时间戳8字节 47~54
     *
     * @return
     */
    public static byte[] getTimestamp() {
        SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date nowDate = new Date();
        String timecs = "2019-08-01 08:57:00";
        try {
            nowDate = myFormatter.parse(timecs);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Date lastDate = null;
        try {
            lastDate = myFormatter.parse("1904-01-01 08:00:00");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        double timeValue = (nowDate.getTime() - lastDate.getTime()) / 1000;
        byte[] cs = BitConverterUtil.longToHexBytesBig(Double.doubleToLongBits(timeValue));
        System.out.println(BitConverterUtil.byteArrayToHexStr(cs));
        return BitConverterUtil.longToHexBytesBig(Double.doubleToLongBits(timeValue));
    }
}
